package helper

import (
	"strings"
	
	"github.com/go-ini/ini"
	"pingce/core/vars"
)

func ParseIni(iniPath string) vars.MapStr {
	cfg, err := ini.LoadSources(ini.LoadOptions{SkipUnrecognizableLines: true}, iniPath)
	if err != nil {
		Dry("ini文件不存在")
	}
	
	app, err := cfg.GetSection("APP")
	iniMap := make(vars.MapStr, 0)
	if err != nil {
		iniMap["default_timezone"] = "Asia/Shanghai"
	} else {
		for _, key := range app.Keys() {
			iniMap[strings.ToLower(key.Name())] = key.Value()
		}
	}
	
	db, err := cfg.GetSection("DATABASE")
	if err != nil {
		Dry("ini文件中没有配置数据库项")
	}
	
	for _, key := range db.Keys() {
		iniMap[strings.ToLower(key.Name())] = key.Value()
	}
	
	return iniMap
}

func GetCacheConfig(iniPath string) vars.MapAny {
	cfg, err := ini.LoadSources(ini.LoadOptions{SkipUnrecognizableLines: true}, iniPath)
	if err != nil {
		Dry("ini文件不存在")
	}
	
	app, err := cfg.GetSection("default")
	iniMap := make(vars.MapAny, 0)
	if err != nil {
		iniMap["default"] = "file"
	} else {
		for _, key := range app.Keys() {
			iniMap[strings.ToLower(key.Name())] = key.Value()
		}
	}
	
	db, err := cfg.GetSection("file")
	if err != nil {
		Dry("ini文件中没有配置缓存file项")
	}
	
	tmp := make(map[string]string)
	for _, key := range db.Keys() {
		tmp[strings.ToLower(key.Name())] = key.Value()
	}
	iniMap["file"] = tmp
	
	db, err = cfg.GetSection("redis")
	if err != nil {
		Dry("ini文件中没有配置缓存redis项")
	}
	
	tmp = make(map[string]string)
	for _, key := range db.Keys() {
		tmp[strings.ToLower(key.Name())] = key.Value()
	}
	iniMap["redis"] = tmp
	
	return iniMap
}

func GetVal(arr []vars.MapStr, key string) string {
	for _, v := range arr {
		if v["key"] == key {
			return v["value"]
		}
	}
	
	return ""
}
